#!/bin/sh -e
### BEGIN INIT INFO
# Provides:             wdl
# Required-Start:       $syslog $remote_fs
# Required-Stop:        $syslog $remote_fs
# Should-Start:         $local_fs
# Should-Stop:          $local_fs
# Default-Start:        2 3 4 5 6
# Default-Stop:         0 1 6
# Short-Description:    hushitong health care system
# Description:          Startup script for hushitong health care system. This script is installed in folder /etc/init.d by script 
#                       install-rc-cron.sh. When machine reboots this script will be executed by Linux automatically and starts 
#                       hushitong health care system processes.
### END INIT INFO

command=$1

start() {
  echo "INFO: Starting hushitong application...\n"
  if [ ! -d /opt/hushitong/logs ]; then
    mkdir -p /opt/hushidong/logs
  fi
  echo "INFO: Starting keycloak ...\n"
  /opt/hushitong/keycloak/bin/standalone.sh &
  echo "INFO: Starting prometheus ...\n"
  /opt/hushitong/prometheus/prometheus --config.file="/opt/hushitong/prometheus/prometheus.yml" --storage.tsdb.retention=2d --storage.tsdb.path="/opt/hushitong/prometheus/data" &
  echo "INFO: Starting datarest ...\n"
  /opt/hushitong/datarest/launchServer.sh
  echo "INFO: Starting webserver ...\n"
  /opt/hushitong/webserver/launchServer.sh  
  check
}

stop() {
  echo "INFO: Stopping hushitong application...\n"
  tpid=`ps -ef|grep datarest|grep -v grep|grep -v kill|awk '{print $2}'`
  if [ ${tpid} ]; then
    echo 'Stop datareset process!'
    kill -9 $tpid
  fi
  tpid=`ps -ef|grep webserver|grep -v grep|grep -v kill|awk '{print $2}'`
  if [ ${tpid} ]; then
    echo 'Stop webserver [rocess!'
    kill -9 $tpid
  fi
  tpid=`ps -ef|grep prometheus|grep -v grep|grep -v kill|awk '{print $2}'`
  if [ ${tpid} ]; then
    echo 'Stop prometheus process!'
    kill -9 $tpid
  fi
  tpid=`ps -ef|grep keycloak|grep -v grep|grep -v kill|awk '{print $2}'`
  if [ ${tpid} ]; then
    echo 'Stop keycloak process!'
    kill -9 $tpid
  fi
}

check() {
  tpid=`ps -ef|grep datarest|grep -v grep|grep -v kill|awk '{print $2}'`
  if [ ${tpid} ]; then
    echo 'INFO: Process datarest is running.'
  else
    echo 'ERROR: Process datarest is NOT running.'
  fi
  tpid=`ps -ef|grep webserver|grep -v grep|grep -v kill|awk '{print $2}'`
  if [ ${tpid} ]; then
    echo 'INFO: Process webserver is running.'
  else
    echo 'ERROR: Process webserver is NOT running.'
  fi
    tpid=`ps -ef|grep prometheus|grep -v grep|grep -v kill|awk '{print $2}'`
  if [ ${tpid} ]; then
    echo 'INFO: Process prometheus is running.'
  else
    echo 'ERROR: Process prometheus is NOT running.'
  fi
    tpid=`ps -ef|grep keycloak|grep -v grep|grep -v kill|awk '{print $2}'`
  if [ ${tpid} ]; then
    echo 'INFO: Process keycloak is running.'
  else
    echo 'ERROR: Process keycloak is NOT running.'
  fi
}

case ${command} in
start)
  start
  ;;
stop)
  stop
  ;;
check)
  check
  ;;
*)
  echo "Unknown argument: ${command}"
  exit 1
esac

exit 0
